<template>
  <div class="app-container approval">
    <el-form class="alone-business" :model="queryApproval" ref="queryApprovalRef" :inline="true" label-width="68px">
      <el-form-item label="审批类型" prop="approvalSetId">
        <el-select v-model="queryApproval.approvalSetId" placeholder="请选择" clearable style="width: 240px">
          <el-option :value="1" label="设置工厂返佣"></el-option>
          <el-option :value="2" label="取消工厂返佣"></el-option>
          <el-option :value="3" label="调整续约返佣"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="租户名称" prop="tenantName">
        <el-input v-model="queryApproval.tenantName" placeholder="请输入租户名称" clearable style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getTable">搜索</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="queryApproval.approvalType" class="demo-tabs" @tab-change="changeTab">
      <el-tab-pane label="待我审批" name="1"></el-tab-pane>
      <el-tab-pane label="我已审批" name="2"></el-tab-pane>
    </el-tabs>

    <el-table v-loading="loading" :data="approvalTable" highlight-current-row style="width: 100%; margin-top: 20px">
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column property="approvalName" label="审批类型" />
      <el-table-column property="tenantName" label="租户名称" width="250" />
      <el-table-column property="applyUserName" label="申请人" />
      <el-table-column property="applyTime" label="申请时间" />
      <el-table-column property="approvalTime" label="审批时间" v-if="queryApproval.approvalType == '2'" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button v-if="queryApproval.approvalType == '1'" link type="primary" @click="openApproval(scope.row, scope.$index)">
            审批确认
          </el-button>
          <el-button v-if="queryApproval.approvalType == '2'" link type="primary" @click="openApproval(scope.row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listTotal"
      v-model:page="queryApproval.current"
      v-model:limit="queryApproval.size"
      @pagination="getTable"
    />
    <!-- 审核抽屉 -->
    <el-drawer title="工厂返佣" v-model="drawerVisible" @close="closeDeawer" size="550px" class="approval-drawer" append-to-body>
      <el-alert class="alert-primary" :closable="false" show-icon>
        <template #title>
          <div>系统暂不支持打回功能，如存在问题请线下联系申请人处理</div>
        </template>
      </el-alert>

      <!-- <el-alert class="alert-primary" :closable="false" show-icon>
        <template #title>
          <div>该申请单存在不符合业务规则的情况，请谨慎审批：</div>
        </template>
        <template #default>
          <p>1、工厂营销返佣比例不能低于2%</p>
          <p>2、工厂返佣阶梯中最高档返佣比例不能低于2%</p>
          <p>3、根据工厂主营品类，最高档目标金额不能高于规定值</p>
        </template>
      </el-alert> -->

      <div class="spase" v-loading="drawerLoading">
        <!-- <el-scrollbar max-height="calc(100vh - 90px)"> -->
        <el-form style="width: 100%" label-position="top" :model="approvalForm" label-width="80px">
          <el-form-item label="审批类型">
            <div>{{ approvalForm.approvalName }}</div>
          </el-form-item>
          <el-form-item label="取消原因" v-if="approvalForm.type === 2">
            <div class="text-wrap">{{ approvalForm.cancelReason }}</div>
          </el-form-item>
          <el-form-item label="调整原因" v-if="approvalForm.type === 3">
            <div class="text-wrap">{{ approvalForm.changeReason }}</div>
          </el-form-item>
          <el-form-item label="租户名称">
            <div>{{ approvalForm.tenantName }}</div>
          </el-form-item>
          <!-- 不等于续约调整 -->
          <template v-if="approvalForm.type !== 3">
            <!-- 不等与营销返点调整 -->
            <template v-if="approvalForm.type !== 4">
              <el-form-item label="返佣状态" v-if="queryApproval.approvalType == 1">
                <div>{{ approvalForm.status === 1 ? "待审批" : "" }}</div>
              </el-form-item>
              <el-form-item label="返佣开始时间">
                <div>{{ approvalForm.startTime }}</div>
              </el-form-item>
              <el-form-item label="返佣周期">
                <div>{{ approvalForm.cycle === 1 ? "年" : "" }}</div>
              </el-form-item>
              <el-form-item label="到期是否续约">
                <div>{{ approvalForm.renew === 0 ? "不自动续约" : "自动续约" }}</div>
              </el-form-item>
              <el-form-item label="营销返点">
                <div>{{ approvalForm.cpaFactorySalesRebateDetailVo?.salesRebatesRatio }}%</div>
              </el-form-item>
              <el-form-item label="营销返佣分配">
                <el-table :data="approvalForm?.marketTable" highlight-current-row style="width: 100%; border: 1px solid #e9e9eb">
                  <el-table-column property="name" label="分配对象"></el-table-column>
                  <el-table-column property="commissionRatio" label="返点（%）"></el-table-column>
                </el-table>
              </el-form-item>
              <!-- 无续约返点设置显示table -->
              <el-form-item label="集采返点">
                <div style="width: 100%; border: 1px solid #e9e9eb">
                  <el-table :data="approvalForm.cpaFactoryRatioDetailVos" highlight-current-row style="width: 100%">
                    <el-table-column property="amount" label="销售金额（W）"></el-table-column>
                    <el-table-column property="commissionRatio" label="厂家返点（%）"></el-table-column>
                  </el-table>
                </div>
              </el-form-item>
              <el-form-item label="备注说明">
                <div class="text-wrap">{{ approvalForm.remark }}</div>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item label="编辑前营销返点">
                <div>{{ approvalForm.oldFactorySalesRebateDetailVo?.salesRebatesRatio }}%</div>
              </el-form-item>
              <el-form-item label="编辑前营销返佣分配">
                <el-table
                  :data="approvalForm?.oldMarketTable"
                  highlight-current-row
                  style="width: 100%; border: 1px solid #e9e9eb"
                >
                  <el-table-column property="name" label="分配对象"></el-table-column>
                  <el-table-column property="commissionRatio" label="返点（%）"></el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item label="编辑后营销返点">
                <div>{{ approvalForm.newFactorySalesRebateDetailVo?.salesRebatesRatio }}%</div>
              </el-form-item>
              <el-form-item label="编辑后营销返佣分配">
                <el-table
                  :data="approvalForm?.newMarketTable"
                  highlight-current-row
                  style="width: 100%; border: 1px solid #e9e9eb"
                >
                  <el-table-column property="name" label="分配对象"></el-table-column>
                  <el-table-column property="commissionRatio" label="返点（%）"></el-table-column>
                </el-table>
              </el-form-item>
            </template>
          </template>
          <!-- 有续约返点设置后显示table -->
          <el-form-item label="集采返点" v-else>
            <el-row style="width: 100%; border: 1px solid #e9e9eb">
              <el-table :data="approvalForm.oldCpaFactoryRatioDetailVos" highlight-current-row style="width: 50%">
                <el-table-column label="续约前">
                  <el-table-column label="销售金额（W）" prop="amount"> </el-table-column>
                  <el-table-column label="厂家返点（%）" prop="commissionRatio"></el-table-column>
                </el-table-column>
              </el-table>
              <el-table :data="approvalForm.newCpaFactoryRatioDetailVos" highlight-current-row style="width: 50%">
                <el-table-column label="续约后">
                  <el-table-column label="销售金额（W）" prop="amount"> </el-table-column>
                  <el-table-column label="厂家返点（%）" prop="commissionRatio"></el-table-column>
                </el-table-column>
              </el-table>
            </el-row>
          </el-form-item>
        </el-form>
        <!-- </el-scrollbar> -->
      </div>

      <template #footer v-if="queryApproval.approvalType == '1'">
        <el-row class="row-bg" justify="space-between" align="middle">
          <div>
            <el-space direction="vertical" alignment="flex-start">
              <el-text class="mx-1">申请人：{{ approvalForm.applyUserName }}</el-text>
              <el-text class="mx-1" type="info">{{ approvalForm.applyTime }}</el-text>
            </el-space>
          </div>
          <div>
            <el-button type="primary" plain @click="openApprovalDialog(true)">同意并继续审核下一个</el-button>
            <el-button type="primary" @click="openApprovalDialog(false)">同 意</el-button>
          </div>
        </el-row>
      </template>
    </el-drawer>

    <!-- 同意审批 弹窗-->
    <el-dialog v-model="approvalDialog" width="474" :close-on-click-modal="false" @close="closeApprovalDialog">
      <div style="text-align: center">
        <el-icon color="#F56C6C" size="70"><Warning /></el-icon>
      </div>
      <div style="text-align: center; margin-top: 40px; margin-bottom: 30px">请确认是否审批通过！</div>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeApprovalDialog">取消</el-button>
          <el-button class="btn" :loading="buttonLoading" type="primary" @click="handelSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { pendingPage, finishPage, approvalDetail, approvalPass } from "@/api/index";
import { ref, onMounted } from "vue";
import useCodeArrStore from "@/store/modules/select";
import { getOptionselect } from "@/api/login";

const getCodeArr = () => {
  getOptionselect().then(res => {
    useCodeArrStore().setDict(res.data);
  });
};
onMounted(() => {
  getCodeArr();
});

// 搜索条件
const queryApproval = ref({
  approvalSetId: "",
  tenantName: "",
  approvalType: "1",
  current: 1,
  size: 10
});
const queryApprovalRef = ref();

// 搜索重置
const reset = () => {
  queryApproval.value = {
    approvalSetId: "",
    tenantName: "",
    approvalType: queryApproval.value.approvalType,
    current: 1,
    size: 10
  };
  getTable();
};

// tab标签变化
const changeTab = value => {
  getTable();
};

// 审核表格
const approvalTable = ref([]);
const loading = ref(false);
// 审核表格总数
const listTotal = ref(0);

// 获取表格数据
const getTable = () => {
  loading.value = true;
  if (queryApproval.value.approvalType == 1) {
    pendingPage(queryApproval.value).then(res => {
      res.data.records?.forEach(item => {
        item.applyTime = item.applyTime?.split(" ")[0];
      });
      approvalTable.value = res.data.records;
      listTotal.value = res.data.total;
      loading.value = false;
      if (isNext.value) {
        if (tableIndex.value >= approvalTable.value.length) {
          isNext.value = false;
          closeDeawer();
        } else {
          getApprovalDetail(approvalTable.value[tableIndex.value]);
        }
      }
    });
  } else {
    finishPage(queryApproval.value).then(res => {
      res.data.records?.forEach(item => {
        item.applyTime = item.applyTime?.split(" ")[0];
        item.approvalTime = item.approvalTime?.split(" ")[0];
      });
      approvalTable.value = res.data.records;
      listTotal.value = res.data.total;
      loading.value = false;
    });
  }
};

// 审核抽屉
const drawerVisible = ref(false);
const drawerLoading = ref(false);
const tableIndex = ref(0);
// 打开审核抽屉
const openApproval = (row, index) => {
  drawerVisible.value = true;
  drawerLoading.value = true;
  tableIndex.value = index;
  getApprovalDetail(row);
};
// 是否同意并继续审核下一个
const isNext = ref(false);
// 获取审核详情
const getApprovalDetail = row => {
  approvalDetail(row.approvalId).then(res => {
    // 调整续约审批详情
    res.data.cpaChangeRenewDetailVo?.newCpaFactoryRatioDetailVos.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.commissionRatio);
    });
    res.data.cpaChangeRenewDetailVo?.oldCpaFactoryRatioDetailVos.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.commissionRatio);
    });
    // 取消工厂返佣审批详情
    res.data.cpaFactoryCancelDetailVo?.cpaFactoryRatioDetailVos.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.commissionRatio);
    });
    if (res.data.cpaFactoryCancelDetailVo) {
      returnCpaFactorySetDetailVo(res.data.cpaFactoryCancelDetailVo, "cpaFactorySalesRebateDetailVo", "marketTable");
    }
    // 设置工厂返佣审批详情
    res.data.cpaFactorySetDetailVo?.cpaFactoryRatioDetailVos.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.commissionRatio);
    });
    if (res.data.cpaFactorySetDetailVo) {
      returnCpaFactorySetDetailVo(res.data.cpaFactorySetDetailVo, "cpaFactorySalesRebateDetailVo", "marketTable");
    }

    // 调整工厂营销返点审批详情
    if (res.data.cpaChangeSalesDetailVo) {
      returnCpaFactorySetDetailVo(res.data.cpaChangeSalesDetailVo, "newFactorySalesRebateDetailVo", "newMarketTable");
      returnCpaFactorySetDetailVo(res.data.cpaChangeSalesDetailVo, "oldFactorySalesRebateDetailVo", "oldMarketTable");
    }

    // 根据type不同，展示不同的dom
    // type 1:设置返佣，2：取消返佣，3：调整续约，4：营销调整
    if (res.data.cpaChangeRenewDetailVo) {
      approvalForm.value = { ...row, ...res.data.cpaChangeRenewDetailVo, ...{ type: 3 } };
    } else if (res.data.cpaFactoryCancelDetailVo) {
      res.data.cpaFactoryCancelDetailVo.startTime = res.data.cpaFactoryCancelDetailVo.startTime?.split(" ")[0];
      approvalForm.value = { ...row, ...res.data.cpaFactoryCancelDetailVo, ...{ type: 2 } };
    } else if (res.data.cpaFactorySetDetailVo) {
      res.data.cpaFactorySetDetailVo.startTime = res.data.cpaFactorySetDetailVo.startTime?.split(" ")[0];
      approvalForm.value = { ...row, ...res.data.cpaFactorySetDetailVo, ...{ type: 1 } };
    } else if (res.data.cpaChangeSalesDetailVo) {
      approvalForm.value = { ...row, ...res.data.cpaChangeSalesDetailVo, ...{ type: 4 } };
    }
    drawerLoading.value = false;
    isNext.value = false;
  });
};

// 营销返点、营销返佣分配数据回显
const returnCpaFactorySetDetailVo = (value, key, tableKey) => {
  value[tableKey] = [
    {
      name: "工厂开拓人员",
      commissionRatio: Number(value[key]?.introducerRatio) || null
    },
    {
      name: "渠道",
      commissionRatio: Number(value[key]?.channelRatio) || null
    },
    {
      name: "展厅",
      commissionRatio: Number(value[key]?.exhibitionHallRatio) || null
    },
    {
      name: "家装通",
      commissionRatio: Number(value[key]?.platformRatio) || null
    }
  ];
};

// 审核表单
const approvalForm = ref({});

// 关闭抽屉
const closeDeawer = () => {
  drawerVisible.value = false;
  drawerLoading.value = false;
};

const approvalDialog = ref(false);
// 打开同意审批弹窗
const openApprovalDialog = isBoolean => {
  isNext.value = isBoolean;
  approvalDialog.value = true;
};
// 关闭同意审批弹窗
const closeApprovalDialog = () => {
  approvalDialog.value = false;
  buttonLoading.value = false;
};

// 提交按钮loading
const buttonLoading = ref(false);

// 同意弹窗确认
const handelSubmit = () => {
  buttonLoading.value = true;
  approvalPass(approvalForm.value.approvalId).then(res => {
    console.log(isNext.value);
    if (isNext.value) {
      closeApprovalDialog();
      ElMessage.success("审批成功");
      drawerLoading.value = true;
      getTable();
    } else {
      closeApprovalDialog();
      closeDeawer();
      ElMessage.success("审批成功");
      getTable();
    }
  });
};

onMounted(() => {
  getTable();
});
</script>

<style lang="scss" scoped>
.btn {
  width: 120px;
  height: 36px;
  line-height: 36px;
}
</style>
<style lang="scss">
.approval {
  &-drawer {
    .el-drawer__header {
      margin-bottom: 0;
      padding-bottom: 10px;
      border-bottom: 1px solid #dcdfe6;
    }
    .el-drawer__body {
      padding: 0;
      .alert-primary {
        background-color: #e3f0fe;
        color: #000;
        .el-alert__icon {
          color: #0052d9;
        }
        .el-alert__content {
          width: 100%;
        }
        &-title {
          display: flex;
          justify-content: space-between;
        }
      }
      .spase {
        padding: 20px;
      }
    }

    .text-wrap {
      width: 100%;
      text-wrap: wrap;
      word-wrap: break-word;
    }
  }

  .el-dialog {
    margin-top: 200px;
  }
}
</style>
